package com.hzzftech.watchdog.busi.core.executor.utils;

import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.domain.KtDispatcher;
import com.hzzftech.watchdog.busi.domain.KtDispatcherFailedMsg;
import com.hzzftech.watchdog.busi.service.IKtDispatcherFailedMsgService;
import com.hzzftech.watchdog.busi.service.IKtDispatcherService;
import com.hzzftech.watchdog.common.core.domain.entity.SysUser;
import com.hzzftech.watchdog.common.utils.StringUtils;
import com.hzzftech.watchdog.common.utils.spring.SpringUtils;
import com.hzzftech.watchdog.system.service.ISysUserService;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.trans.TransConfiguration;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.www.PrepareExecutionTransServlet;
import org.pentaho.di.www.RegisterTransServlet;
import org.pentaho.di.www.StartExecutionTransServlet;
import org.pentaho.di.www.WebResult;
import org.pentaho.metastore.api.IMetaStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TransExecuteUtil {

    public static Logger logger = LoggerFactory.getLogger(TransExecuteUtil.class);

    public static String sendToSlaveServer(TransMeta meta, TransExecutionConfiguration configuration, IMetaStore metaStore) throws KettleException {
        String carteId;
        SlaveServer slaveServer = configuration.getRemoteServer();

        if (slaveServer == null) {
            throw new KettleException("no slave server specified");
        }

        if (Utils.isEmpty(meta.getName())) {
            throw new KettleException("the transformation needs a name to uniquely it by on the remote server.");
        }

        slaveServer.getLogChannel().setLogLevel(configuration.getLogLevel());

        Map<String, String> vars = new HashMap<>();

        /**
         * 执行参数的构造
         */
        for (String var : Const.INTERNAL_TRANS_VARIABLES) {
            vars.put(var, meta.getVariable(var));
        }
        for (String var : Const.INTERNAL_JOB_VARIABLES) {
            vars.put(var, meta.getVariable(var));
        }
        configuration.getVariables().putAll(vars);
        slaveServer.injectVariables(configuration.getVariables());
        slaveServer.getLogChannel().setLogLevel(configuration.getLogLevel());
        try{
            String xml = new TransConfiguration(meta, configuration).getXML();
            if (logger.isDebugEnabled()) {
                logger.debug("ktr xml content: {}",xml);
            }

            // 发送xml信息到carte服务
            String reply = slaveServer.sendXML(xml, RegisterTransServlet.CONTEXT_PATH + "/?xml=Y");
            WebResult webResult = WebResult.fromXMLString(reply);
            if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
                throw new KettleException("there was an error posting the transformation on the remote server: "+Const.CR+webResult.getMessage());
            }

            // 准备执行任务
            carteId = webResult.getId();
            String pareReply = slaveServer.execService(PrepareExecutionTransServlet.CONTEXT_PATH + "/?name=" + URLEncoder.encode(meta.getName(), "UTF-8") + "&xml=Y&id=" + carteId);
            WebResult pareWebResult = WebResult.fromXMLString(pareReply);
            if (!pareWebResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
                throw new KettleException("there was an error preparing the transformation for execution on the server: "+Const.CR+pareWebResult.getMessage());
            }

            // 开始执行trans
            reply = slaveServer.execService(StartExecutionTransServlet.CONTEXT_PATH +"/?name="+URLEncoder.encode(meta.getName(), "UTF-8")+"&xml=Y&id="+carteId);
            webResult = WebResult.fromXMLString(reply);
            if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
                throw new KettleException("there was an error starting the transformation on the remote: "+Const.CR+webResult.getResult());
            }
            return carteId;
        } catch (Exception e) {
            logger.error("发送任务【carte】：", e);
            throw new KettleException(e);
        }
    }
}
